import zhCN from 'antd/locale/zh_CN';
import {AppRouter} from "@/AppRouter.tsx";
import {ConfigProvider, message, notification, theme} from "antd";
import {MessageInstance} from "antd/es/message/interface";
import {NotificationInstance} from "antd/es/notification/interface";
import useThemeStore, {isDarkMode} from "@/store/ThemeStore.ts";
import {useEffect} from "react";
import useAppState from "@/store/AppState.ts";
import {debounce} from "@/utils/Util.ts";
import {ThemeProvider} from "antd-style";

declare global {
    interface Window {
        messageApi: MessageInstance,
        notificationApi: NotificationInstance
    }
}

const App = () => {
    const [messageApi, contextHolder] = message.useMessage({
        top: '30%',
    })
    const [notificationApi, notificationContextHolder] = notification.useNotification()

    // 注册消息提示框
    window.messageApi = messageApi
    window.notificationApi = notificationApi

    // 控制样式
    const themeData = useThemeStore(state => state.theme)
    if (themeData.type == 'default') {
        themeData.type = isDarkMode() ? 'dark' : 'light'
    }
    if (themeData.type == 'dark') {
        document.documentElement.classList.add('dark')
    } else {
        document.documentElement.classList.remove('dark')
    }

    // 设置页面宽度相应
    const appState = useAppState();
    useEffect(() => {
        const onResize = debounce(() => {
            appState.setWidth(window.innerWidth)
        })
        window.addEventListener('resize', onResize)
        return () => {
            window.removeEventListener('resize', onResize)
        }
    }, []);

    return (
        <ThemeProvider
            appearance={themeData.type}
            theme={{
                algorithm: themeData.type == 'dark' ? theme.darkAlgorithm : theme.defaultAlgorithm,
                token: {
                    colorPrimary: themeData.color,
                },
            }}
        >
            <ConfigProvider
                locale={zhCN}
            >
                <AppRouter/>
                {contextHolder}
                {notificationContextHolder}
            </ConfigProvider>
        </ThemeProvider>
    )
}

export default App
